package com.itic.mall.mobile.ywym;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.Constants;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.type.GoodsType;
import com.itic.appbase.framework.type.UserType;
import com.itic.appbase.framework.utils.IpAddressHelper;
import com.itic.appbase.framework.utils.RandomOrderNumHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpu;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample.Criteria;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.ywym.goods.persistence.model.YwymGoods;
import com.itic.mall.system.ywym.goods.persistence.model.YwymGoodsExample;
import com.itic.mall.system.ywym.goods.service.YwymGoodsService;
import com.itic.mall.system.ywym.timer.persistence.model.YwymTimer;
import com.itic.mall.system.ywym.timer.persistence.model.YwymTimerExample;
import com.itic.mall.system.ywym.timer.service.YwymTimerService;

/**
 * 友惠中心
 * 
 * @author 许小宝
 * @date 2017年12月22日 上午10:33:24
 */
@Controller
@RequestMapping(value = "/mobile/ywym")
public class YwymInterface extends BaseMobileInterface {
	
	  @Autowired
	  private YwymGoodsService ywymGoodsService;
	  
	  @Autowired
	  private YwymTimerService ywymTimerService;
	  
	  //商品过滤字段
	    protected static String[] commonIgnoreProperties = new String[] { "createUser", "isEffective", "updateTime", "note",
	  			"createTime", "orgCode" };

	  
	   /**
	    * APPwebsocket消息推送
	    * @return
	    */
	   @RequestMapping(value="/index")
	   public String index( HttpServletRequest request, Model model, String userid ){
		   model.addAttribute("wsurl", iticJsonMapper.toJson( IpAddressHelper.getLocalhostWs(request) ) );
		   UsersMall user = usersMallService.get(userid);
		   if( null != user ){
			   request.getSession().setAttribute(Constants.WS_USER_NAME, user.getId());//如果不是游客就用用户的id
		   }else{
			   request.getSession().setAttribute(Constants.WS_USER_NAME, RandomOrderNumHelper.getOrderNumber());//游客都给一个随机的号码吧
		   }
		   return "mall/mobile/ywym/index";
	   }
	   
	   /**
	    * 一物一码时间展示
	    * @return
	    */
	   @RequestMapping(value="/timer")
	   @ResponseBody
	   public Map<String,Object> timer( HttpServletRequest request, Model model,HttpServletResponse response, String userid ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		
		   		Map<String, Object> dataMap = new HashMap<String,Object>();
		   		
		   		YwymTimerExample example = new YwymTimerExample();
		   		com.itic.mall.system.ywym.timer.persistence.model.YwymTimerExample.Criteria criteria = example.createCriteria();
		   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		   		if( StringHelper.isNotBlank(userid) ){
		   			criteria.andUserIdEqualTo(userid);
		   		}
		   		
		   		List<YwymTimer> list = ywymTimerService.list(example);
		   		if( list.size()==0 ){
		   			list = getDefaultTimer();
		   		}
		   		
		   		YwymBannerVo bannerVo = new YwymBannerVo();
		   		bannerVo.setWord("友惠家加盟抢线：07986305359");
		   		bannerVo.setQcode("https://uhuijia-1254600872.cos.ap-beijing.myqcloud.com/8bbf5b85-a91a-412f-95ad-6e7c6428da7e.jpg");
		   		
		   		dataMap.put("list", ValueHelper.tranList2MapList(list,commonIgnoreProperties));
		   		dataMap.put("isUpdate", "none");//updated
		   		dataMap.put("banner", bannerVo);
		   		resultMap.put(DATA, dataMap);
		   		
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("YwymInterface", "timer", e.toString(),"一物一码时间展示",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   /**
	     * 获取默认时间配置
	     * @return
	     */
	    private List<YwymTimer> getDefaultTimer() {
	    	YwymTimerExample example = new YwymTimerExample();
	       	example.setOrderByClause("START_TIME ASC");
	       	com.itic.mall.system.ywym.timer.persistence.model.YwymTimerExample.Criteria criteria = example.createCriteria();
	       	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	       	criteria.andUserIdIsNull();
	       	List<YwymTimer> list = ywymTimerService.list(example);
	       	return list;
		}
	   

	   /**
	    * 一物一码首页展示
	    * @return
	    * */
	   @RequestMapping(value="/list")
	   @ResponseBody
	   public Map<String,Object> list( HttpServletRequest request,HttpServletResponse response, String userid ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		if( StringHelper.isNotBlank(userid) ){
		   			UsersMall user = usersMallService.get(userid);
		   			if( null != user && UserType.ydz.getType().equals(user.getType()) ){
		   				
		   				GoodsSpuExample example = new GoodsSpuExample();
		   				
				   		Criteria criteria = example.createCriteria();
				   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				   		criteria.andIsShowEqualTo(DBConst.TRUE);
				   		criteria.andIdIn(getIdsByUserid(userid));
				   		
				   		List<GoodsSpu> listTemp = goodsSpuService.list(example);
				   		List<YwymVo> list = new ArrayList<YwymVo>();
				   		if( listTemp.size()>0 ){
				   			for( GoodsSpu temp : listTemp ){
				   				YwymVo vo = getYwymVoBySpu(temp,user);
				   				list.add(vo);
				   			}
				   		}
				   		resultMap.put(DATA, list);
				   		errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
		   			}else{
		   				errorCode = Not_OPEND_YDZ_ERROR_CODE;
				       	errorMsg = Not_OPEND_YDZ_ERROR_MSG;
		   			}
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("YwymInterface", "index", e.toString(),"一物一码首页展示",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   
	   public List<String> getIdsByUserid( String userid ){
		   
		   YwymGoodsExample example = new YwymGoodsExample();
		   example.setOrderByClause("UPDATE_TIME DESC");
		   com.itic.mall.system.ywym.goods.persistence.model.YwymGoodsExample.Criteria criteria = example.createCriteria();
		   criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		   criteria.andUserIdEqualTo(userid);
		   List<YwymGoods> list = ywymGoodsService.list(example);
		   if( list.size()==0 ){
			    list = getDefaultGoods();
		   }
		   
		   ArrayList<String> ids = new ArrayList<String>();
		   if( list.size()>0 ){
			   for( YwymGoods temp: list ){
				   ids.add(temp.getSpuId());
			   }
		   }
		   return ids;
		   
	   }
	   
	   /*
	    * 获得默认商品
	    */
	   public List<YwymGoods> getDefaultGoods(){
		   YwymGoodsExample example = new YwymGoodsExample();
		   example.setOrderByClause("UPDATE_TIME DESC");
		   com.itic.mall.system.ywym.goods.persistence.model.YwymGoodsExample.Criteria criteria = example.createCriteria();
		   criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		   criteria.andUserIdIsNull();
		   List<YwymGoods> list = ywymGoodsService.list(example);
		   return list;
	   }
	    

	   /**
	    * 一物一码商品详情
	    * @return
	    */
	   @RequestMapping(value="/detail")
	   @ResponseBody
	   public Map<String,Object> detail( HttpServletRequest request,HttpServletResponse response,String id,String userid ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		if( StringHelper.isNotBlank(userid) ){
		   			UsersMall user = usersMallService.get(userid);
		   			if( null != user && UserType.ydz.getType().equals(user.getType()) ){
		   				GoodsSpu goodsSpu = goodsSpuService.get(id);
				   		if( null != goodsSpu ){
				   			
				   			YwymVo ywymVo = getYwymVoBySpu(goodsSpu,user);
					   		resultMap.put(DATA, ywymVo);
					   		
					   		errorCode = SUCCESS_ERROR_CODE;
					       	errorMsg = SUCCESS_ERROR_MSG;
					       	
				   		}else{
				   			errorCode = GOODS_NOT_FIND_ERROR_CODE;
					       	errorMsg = GOODS_NOT_FIND_ERROR_MSG;
				   		}
		   			}else{
		   				errorCode = Not_OPEND_YDZ_ERROR_CODE;
				       	errorMsg = Not_OPEND_YDZ_ERROR_MSG;
		   			}
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("YwymInterface", "detail", e.toString(),"一物一码商品详情展示",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   /**
	    * 一物一码是否可以退出按钮
	    * @return
	    */
	   @RequestMapping(value="/isClose")
	   @ResponseBody
	   public Map<String,Object> isClose( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		resultMap.put(DATA, "close");
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("YwymInterface", "isClose", e.toString(),"一物一码是否可以退出按钮",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	
	   
	   /**
	    * 一物一码实体类转换
	    * @param goodsSpu
	    * @return
	    */
	   public YwymVo getYwymVoBySpu( GoodsSpu goodsSpu, UsersMall user ) throws Exception{
		    YwymVo ywymVo = new YwymVo();
	   		ywymVo.setId(goodsSpu.getId());
	   		ywymVo.setName(goodsSpu.getGoodsName());
	   		ywymVo.setMainImageUrl(goodsSpu.getMainImageUrl());
	   		ywymVo.setPrice(goodsSpu.getPrice());
	   		ywymVo.setConPrice(goodsSpu.getConPrice());
	   		ywymVo.setTotalSales(goodsSpu.getTotalSales());
	   		ywymVo.setQcodeUrl( getQcodeUrlByGoodsSpu(goodsSpu,user) );
	   		if( GoodsType.yh.equals(goodsSpu.getSpuPlatform()) ){
	   			ywymVo.setBanners(goodsSpu.getBanners());
		   		ywymVo.setDetailImageUrls(goodsSpu.getDetailImageUrls());
	   		}
	   		return ywymVo;
	   }
	   
	   /**
	    * 获得二维码的链接
	    * @param goodsSpu
	    * @return
	 * @throws Exception 
	    */
	   public String getQcodeUrlByGoodsSpu( GoodsSpu spu, UsersMall user ) throws Exception{
		   String result = "";
		   
		   String tempUrl = "";
		   if( spu.getCouponMoney()>0 ){
			   tempUrl = goodsSpuService.getConErheyiLink(spu.getId(), user.getId());
		   }else{
			   tempUrl = goodsSpuService.getCommonErheyiLink(spu.getId(), user.getId());
		   }
		   //将此链接转换成二维码
		   if( StringHelper.isNotBlank(tempUrl) ){
			   result = getQcodeByString(tempUrl);
		   }else{
			   tempUrl = goodsSpuService.getCommonErheyiLink(spu.getId(), user.getId());
			   if( StringHelper.isNotBlank(tempUrl)){
				   result = getQcodeByString(tempUrl);
			   }
		   }
		   return result;
	   }
}
